<template>
  <div class="model">
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <div class="loginBox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>
      <!-- <ul class="loginTab">
        <li>手机号码登录</li>
        <li>微信扫码登录</li>
      </ul> -->
      <div class="loginTab">
        <a
          href="#"
          :class="{ active: isShowContent }"
          @click="isShowContent = true"
          >手机号码登录</a
        >
        |
        <a href="#" :class="{ active: !isShowContent }" @click="showQrCode"
          >微信扫码登录</a
        >
      </div>
      <div class="loginContent">
        <div class="phoneLogin" v-show="isShowContent">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model.trim="phoneNumber"
            />
          </div>
          <div class="row">
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              :imgs="imgs"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :accuracy="3"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model.trim="msgCode"
            />
            <button class="btn codeBtn" v-if="isShowCount">
              {{ count }}
            </button>
            <button class="btn codeBtn" @click="getCode" v-else>
              获取验证码
            </button>
          </div>
          <button class="login-btn" @click="loginFn">登录</button>
        </div>
        <div id="weixin" class="qrLogin" v-show="!isShowContent">
          微信扫码登录内容
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapActions } from "vuex";
import {
  SendSMSApi,
  PhoneReginApi,
  WeiXinBindApi,
  UserInfoApi,
} from "@/request/api";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowContent: true,
      phoneNumber: "",
      msg: "向右滑动",
      imgs: [
        require("../assets/img/yanlingjijpeg.jpeg"),
        require("../assets/img/150 .jpg"),
        require("../assets/img/1062.jpg"),
        require("../assets/img/916.jpg"),
      ],
      count: 5,
      isShowCount: false,
      msgCode: "",
    };
  },

  methods: {
    ...mapMutations({
      changeIsShowLoginModal: "showModel/changeIsShowLoginModal",

      changeIsLogined: "loginStatus/changeIsLogined",
      //
      changeIsShowToast: "showToast/changeIsShowToast",
    }),
    ...mapActions({
      asyncIsShowToast: "showToast/asyncIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },
    // 封装校验手机号和滑块验证码
    toVerify() {
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请正确地输入手机号");
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "请正确地输入手机号",
          toastType: "warning",
        });
        return;
      }
      if (this.msg == "向右滑动" || this.msg == "再试一次") {
        // alert("请先完成滑块验证");
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "请先完成滑块验证",
          toastType: "warning",
        });
        return;
      }
      return true;
    },
    //2. 验证滑块验证码 ， 不成功 要提示
    // 再试一次，或者 向右滑动
    async getCode() {
      const flag = this.toVerify(); //当前这个方法 验证成功后，才继续后面的操作。
      if (!flag) return;
      const res = await SendSMSApi({
        phone: this.phoneNumber,
      });
      console.log("res", res);
      // [先思考倒计时！！！！！] ---   循环（定时器）递减数字（变量）
      //连续点击时，生成多个定时器，导致倒计时过快;  解决方法 -- 设置两个按钮显示隐藏，显示按钮不设点击事件
      this.isShowCount = true;
      const timer = setInterval(() => {
        this.count--;
        if (this.count == 0) {
          clearInterval(timer);
          this.count = 3;
          this.isShowCount = false;
        }
      }, 1000);
    },
    async loginFn() {
      //  1.验证手机号码  ，不成功 要提示
      //  2. 验证滑块验证码 ， 不成功 要提示  ！！避免弹完手机号或滑块验证，接着又弹验证码验证
      // if (!this.toVerify()) return;
      //  3. 验证手机验证码 ，不成功 要提示 （由于后台没有告诉我们正确的验证码是多少，此处只判断非空）
      if (this.msgCode == "") {
        // alert("短信验证码不能为空！");
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "短信验证码不能为空！",
          toastType: "danger",
        });
        return;
      }
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await WeiXinBindApi({
          phone: this.phoneNumber,
          verifyCode: this.msgCode,
          uuid,
        });
      } else {
        res = await PhoneReginApi({
          phone: this.phoneNumber,
          verifyCode: this.msgCode,
        });
        console.log("登录res", res);
      }
      if (res.code == 0) {
        // alert("登录成功");
        this.asyncIsShowToast({
          isShowToast: true,
          toastMsg: "登录成功",
          toastType: "success",
        });
        // 存储 token
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        this.changeIsShowLoginModal(false);
        this.changeIsLogined(true);

        //1. 删除 已经用不到的 uuid
        localStorage.removeItem("uuid");
        //2. 删除地址栏中的code 借跳转用刷新的方法
        this.$router.push(this.$route.path);

        // 更新用户信息
        /* const user = await UserInfoApi();
        console.log({ user }); */
        this.asyncChangeUserInfo();
        console.log("更新了用户登录信息");
      }
    },
    showQrCode() {
      this.isShowContent = false;
      //获取二维码 并展示
      // 申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICAgIGRpc3BsYXk6IG5vbmU7DQp9",
      });
    },
  },
};
</script>

<style lang="less" scoped>
.model {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
  }
  .loginBox {
    width: 555px;
    height: 423px;
    position: absolute;
    background: url("../assets/img/login-box-bg.png");
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    .close {
      position: absolute;
      width: 22px;
      height: 22px;
      background: url("../assets/img/close.png");
      top: 10px;
      right: 55px;
    }
    .loginTab {
      margin-top: 45px;
      text-align: center;
      a {
        text-decoration: none;
        color: #999999;
        padding: 0 10px;
        // a{.class} 表示是 a 标签，的子元素类名，控制不了 a 的样式  只能控制 a 的子元素样式
        // a{ &.class} = a{class：value} 表示 a 标签的 串连选择器 样式都是作用在 a 标签上
        &.active {
          color: #000;
        }
      }
    }
    .loginContent {
      width: 350px;
      height: 280px;
      margin: 25px auto;
      // background-color: #fcf;
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          input {
            flex: 1;
            height: 50px;
            outline: none;
            border: 1px solid #ccc;
            text-indent: 1em;
          }
          .codeBtn {
            height: 54px;
            line-height: 50px;
            padding: 0 5px;
            background-color: #ddd;
            border: none;
          }
          .btn {
            width: 80px;
            margin-left: 10px;
            cursor: pointer;
          }
        }
        .login-btn {
          width: 100%;
          height: 50px;
          border: none;
          background-color: #0a328e;
          font-size: 18px;
          color: #fff;
          cursor: pointer;
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}

// 滑块样式
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>